package com.thoughtworks.wechatmoments.widget;

import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.thoughtworks.commonlibrary.compat.Image.ImageLoader;
import com.thoughtworks.wechatmoments.R;
;
import java.util.ArrayList;
import java.util.List;

/**
 * 朋友圈9图自定义View
 *
 * @author guowenlong
 */
public class FriendLinearLayout extends LinearLayout {
    private int maxWidth = 0;
    private int max_row;
    private int onePicWidth;
    private int onePicHeight;
    private int multiPicWith;
    private int imagePadding;
    private LayoutParams onePicPara, morePara, moreParaColumnFirst, rowPara;
    private List<String> imagesList = new ArrayList<>();

    public FriendLinearLayout(Context context) {
        this(context, null);
    }

    public FriendLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        onePicWidth = (int) getResources().getDimension(R.dimen.friend_layout_one_pic_width);
        onePicHeight = (int) getResources().getDimension(R.dimen.friend_layout_one_pic_height);
        multiPicWith = (int) getResources().getDimension(R.dimen.friend_layout_multi_pic_width);
        imagePadding = (int) getResources().getDimension(R.dimen.friend_layout_padding);
    }

    public void setList(@NonNull List<String> lists) {
        imagesList = lists;
        if (maxWidth != 0) {
            multiPicWith = (maxWidth - imagePadding * 2) / 3; //解决右侧图片和内容对不齐问题
            onePicWidth = maxWidth - imagePadding * 2;  // 一张图的时候，图片宽度
            initImageLayoutParams();
        }
        initView();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (maxWidth == 0) {
            int width = measureWidth(widthMeasureSpec);
            if (width > 0) {
                maxWidth = width - getPaddingLeft() - getPaddingRight();
                if (imagesList != null && imagesList.size() > 0) {
                    setList(imagesList);
                }
            }
        }
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }

    private int measureWidth(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }

    private void initImageLayoutParams() {
        int wrap = LayoutParams.WRAP_CONTENT;
        int match = LayoutParams.MATCH_PARENT;
        onePicPara = new LayoutParams(onePicWidth, wrap);
        moreParaColumnFirst = new LayoutParams(multiPicWith, multiPicWith);
        morePara = new LayoutParams(multiPicWith, multiPicWith);
        morePara.setMargins(imagePadding, 0, 0, 0);
        rowPara = new LayoutParams(match, wrap);
    }

    private void initView() {
        this.setOrientation(VERTICAL);
        this.removeAllViews();
        if (maxWidth == 0) {
            //为了触发onMeasure()来测量最大宽度
            addView(new View(getContext()));
            return;
        }

        if (imagesList.size() == 1) {
            addView(createImageView(0, false));
        } else {
            int allCount = imagesList.size();
            if (allCount == 4) {
                max_row = 2;
            } else {
                max_row = 3;
            }
            int rowCount = allCount / max_row + (allCount % max_row > 0 ? 1 : 0);// 行数
            for (int rowCursor = 0; rowCursor < rowCount; rowCursor++) {
                LinearLayout rowLayout = new LinearLayout(getContext());
                rowLayout.setOrientation(LinearLayout.HORIZONTAL);
                rowLayout.setLayoutParams(rowPara);
                if (rowCursor != 0) rowLayout.setPadding(0, imagePadding, 0, 0);
                int columnCount = allCount % max_row == 0 ? max_row : allCount % max_row;//每行的列数
                if (rowCursor != rowCount - 1) {
                    columnCount = max_row;
                }
                addView(rowLayout);
                int rowOffset = rowCursor * max_row;// 行偏移
                for (int columnCursor = 0; columnCursor < columnCount; columnCursor++) {
                    int position = columnCursor + rowOffset;
                    rowLayout.addView(createImageView(position, true));
                }
            }
        }
    }

    private ImageView createImageView(final int position, final boolean isMultiImage) {
        String url = "";
        if (!TextUtils.isEmpty(imagesList.get(position))) url = imagesList.get(position);
        ImageView imageView = new ImageView(getContext());
        if (isMultiImage) {
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setLayoutParams(position % max_row == 0 ? moreParaColumnFirst : morePara);
        } else {
            imageView.setAdjustViewBounds(true);
            imageView.setScaleType(ImageView.ScaleType.FIT_START);
            imageView.setMaxHeight(onePicHeight);
            imageView.setLayoutParams(onePicPara);
        }
        imageView.setId(url.hashCode());
        ImageLoader.imageLoad(getContext(), url, imageView, R.mipmap.ic_launcher);
        return imageView;
    }
}